package tk.zater;

import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.regex.Pattern;

public class RandomGenerator implements Iterator<Integer> {
	private int a1;
	private int a2;
	private long currentVal = 1;
	private Strategy st;
	private int filter;
	private int counter = 0;

	public RandomGenerator(int a1, int a2) {
		this.a1=Math.max(a1,a2);
		this.a2=Math.min(a1, a2);
		st = Strategy.Total_Generator;
	}

	public RandomGenerator(int a1, int a2, Strategy st, int filter) {
		this.a1=Math.max(a1,a2);
		this.a2=Math.min(a1, a2);
		
		this.st = st;
		this.filter = filter;

	}

	public boolean hasNext() {
		// TODO Auto-generated method stub
		switch (st) {
		case Total_Generator:
			if (counter >= a1-1) {
				return false;
			} else {
				return true;
			}
		case Basic_Generator:
			if (counter > filter) {
				return false;
			} else {
				return true;
			}
		case Sort_Generator:
			if (counter >= a1-1) {
				return false;
			} else {
				return true;
			}
		default:
			return false;
		}
	}

	public Integer next() {
		switch (st) {
		case Total_Generator:
			counter++;
			return nextVal();
		case Basic_Generator:
			while (true) {
				if (nextVal() <= filter) {
					counter++;
					return (int) currentVal;
				}
			}

		default:
			return 0;
		}
	}

	private int nextVal() {
		currentVal = (currentVal * a2 ) % a1;
		return (int) currentVal;
	}

	class node implements Comparable<node> {
		int key;
		long value;

		public node(int key, long value) {
			this.key = key;
			this.value = value;
		}

		public int compareTo(node o) {
			return Long.compare(o.value, this.value);
		}
	}

	public int[] nextSort() {

		int ret[] = new int[filter];
		PriorityQueue<node> pq = new PriorityQueue<RandomGenerator.node>();
		for (long i = 0; i < filter; i++) {
			pq.add(new node(pq.size() + 1, nextVal()));
			counter++;
		}
		for (int i = 0; i < filter; i++) {
			ret[i] = pq.poll().key;
		}
		return ret;
	}
}
